package com.laolang.thresh.module.auth.service;

import cn.hutool.core.util.StrUtil;
import com.laolang.thresh.module.auth.consts.AuthConsts;
import com.laolang.thresh.module.auth.domain.LoginUser;
import com.laolang.thresh.module.system.user.business.SysUserBusiness;
import com.laolang.thresh.module.system.user.business.SysUserPermBusiness;
import com.laolang.thresh.module.system.user.consts.SysUserEnums.Status;
import com.laolang.thresh.module.system.user.entity.SysUser;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * xxx.
 *
 * @author laolang
 * @version 0.1
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserBusiness sysUserBusiness;
    private final SysUserPermBusiness sysUserPermBusiness;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserBusiness.tryGetByUsername(username);
        if (Objects.isNull(sysUser)) {
            String msg = StrUtil.format("登录用户:[{}] 不存在", username);
            log.info(msg);
            throw new UsernameNotFoundException(msg);
        }

        // 账号是否被锁定
        if (Status.LOCK.getValue().equals(sysUser.getStatus())) {
            log.info("登录用户:[{}] 被锁定", username);
            throw new UsernameNotFoundException(StrUtil.format("对不起, 您的账号:{} 被锁定, 请联系管理员", username));
        }

        // 构造登录用户信息
        LoginUser loginUser = new LoginUser(sysUserPermBusiness.listPermsByUsername(sysUser.getUsername()),
            sysUserPermBusiness.listRolesByUsername(sysUser.getUsername()),
            sysUser);
        if (StrUtil.equals(loginUser.getUsername(), AuthConsts.SUPER_ADMIN_USER_NAME)) {
            loginUser.getRoles().add(AuthConsts.SUPER_ADMIN_ROLE_NAME);
        }
        return loginUser;
    }
}

